package com.example.springback.controller;

import cn.hutool.core.io.FileUtil;
import com.example.springback.common.Result;
import com.example.springback.exception.CustomException;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/files")
public class FilesController {
    //获取当前项目的根路径
    private static final String filePath=System.getProperty("user.dir")+"/files/";
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {//以文件流的形式接受前端上传的文件
        String originFileName=file.getOriginalFilename();
        if(!FileUtil.isDirectory(filePath)){//如果目录不存在需要先创建目录
            FileUtil.mkdir(filePath);//创建一个目录
        }
        //提供文件完整的路径
        String fileName=filePath+originFileName;
        try {
            FileUtil.writeBytes(file.getBytes(),fileName);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("500","文件上传失败");
        }
        //返回一个路径：http://localhost:8080/files/upload/xxx.txt
        return Result.success();
    }
    @GetMapping("/download")
    public void download(@PathVariable String fileName, HttpServletResponse response){
        try {

            response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            response.setContentType("application/octet-stream");
            OutputStream outputStream= response.getOutputStream();
            String realPath=filePath+fileName;
            //获取文件的字节数组
            byte[] bytes=FileUtil.readBytes(realPath);
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();

        } catch (IOException e) {
            throw new CustomException("500","文件下载失败");
        }
    }
}
